package com.kaibes.module.token.listener;

import java.math.BigInteger;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.kaibes.core.base.util.ObjectUtils;
import com.kaibes.module.token.pojo.TokenLog;
import com.kaibes.module.token.pojo.TokenLogType;
import com.kaibes.module.token.service.TokenLogService;
import com.kaibes.module.token.service.TokenService;
import com.kaibes.module.user.UserService;
import com.kaibes.orm.core.listener.InsertListener;
import com.kaibes.orm.curd.Insert;
import com.kaibes.orm.spring.OrmListener;

@OrmListener(service = TokenService.class)
public class TokenInsertListener implements InsertListener<BigInteger> {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenLogService tokenLogService;
    
    @Override
    public void afterInsert(Insert insert, List<BigInteger> ids) throws SQLException {
        try {
            Object token = insert.getDatas().get(0);
            Integer userId = (Integer) ObjectUtils.getField(token, "userId");
            LocalDateTime createTime = (LocalDateTime) ObjectUtils.getField(token, "createTime");
            TokenLog tokenLog = new TokenLog();
            tokenLog.setUserId(userId);
            tokenLog.setType(TokenLogType.CREATE);
            tokenLog.setCreateTime(createTime);
            tokenLogService.save(tokenLog);
            if (userService != null) {
                userService.updateLoginTimeById(userId, createTime);
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}
